import java.lang.reflect.*;

import org.junit.Test;

public class Test6 {
    Class cla;

    {
        try {
            cla = Class.forName("Student");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void Create_obj() throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        //方式一
        Object obj1 = cla.newInstance();//该对象只能调用无参构造方法
        System.out.println(obj1);//需在创建字节码的类中重写toString方法，打印的才不是地址值
        System.out.println("------------------");
        //方式二
        Constructor<Object> c = cla.getConstructor(int.class, String.class);//先获取含参构造函数
        Object obj2 = c.newInstance(18, "陈");//再创建含参构造函数的对象
        System.out.println(obj2);

    }

    @Test
    public void TestC() {
        Constructor[] c = cla.getConstructors();
        for (Constructor cc : c) {
            System.out.println(cc);
        }
    }

    @Test
    public void TestF() {
        Field[] f = cla.getFields();
        for (Field ff : f) {
            System.out.println(ff);
        }
    }

    @Test
    public void TestM() {
        Method[] m = cla.getMethods();
        for (Method mm : m) {
            System.out.println(mm);
        }
    }

    @Test
    public void Violent_Rf() throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, InstantiationException {
        Class cla = Class.forName("Person");
        Field field = cla.getDeclaredField("age");
        field.setAccessible(true);
        Object obj = cla.newInstance();
        field.set(obj, 8);
        System.out.println(field.get(obj));
    }

    @Test
    public void Violent_Rm() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
        Class cla = Class.forName("Person");
        Method method1 = cla.getDeclaredMethod("eat");
        method1.setAccessible(true);
        Object obj = cla.newInstance();
        method1.invoke(obj);//执行方法的函数invoke
        Method method2 = cla.getDeclaredMethod("run", String.class, int.class);
        method2.setAccessible(true);
        method2.invoke(obj, "张", 18);
    }
}
